﻿/*
 * ErrorStackLibrary: provides a .Net object wrapper around ErrorStack.com's REST API
 * Copyright (C) 2009 by Harley Pebley
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the 
 * Free Software Foundation, Inc.
 * 51 Franklin Street, Fifth Floor
 * Boston, MA  02110-1301  USA
 */
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;

namespace ErrorStackLibrary
{
    public class ErrorStackException : Exception
    {
        public ErrorStackException(string message) : base(message) { }
    }

    public class ErrorStack
    {
        public string StackKey { get; private set; }

        public ErrorStack(string stackKey)
        {
            StackKey = Uri.EscapeUriString(stackKey);
        }

        public void Log(IDictionary<string, string> items)
        {
            var request = WebRequest.Create(BuildSubmissionURI(items)) as HttpWebRequest;
            if (request == null)
                throw new ErrorStackException("Could not create WebRequest.");

            var response = request.GetResponse();

            if (response.ResponseUri.ToString() != "http://www.errorstack.com/submit/pixel.gif")
                throw new ErrorStackException("Unexpected response from submission.");
        }

        private Uri BuildSubmissionURI(IEnumerable<KeyValuePair<string, string>> items)
        {
            var result = BuildBaseURI();
            result.Path = "submit";

            var query = new StringBuilder(result.Query.Substring(1));
            foreach (var item in items)
                query.Append("&", Uri.EscapeUriString(item.Key), "=", Uri.EscapeUriString(item.Value));
            result.Query = query.ToString();

            return result.Uri;
        }

        private UriBuilder BuildBaseURI()
        {
            return new UriBuilder
                       {
                           Host = "www.errorstack.com",
                           Query = string.Concat("s=", StackKey)
                       };
        }
    }

    public static class StringBuilderExtensions
    {
        public static void Append(this StringBuilder sb, params string[] strings)
        {
            foreach (var str in strings)
                sb.Append(str);
        }
    }
}
